from pydantic import BaseModel, validator, Field
from typing import Optional, Dict, Any

class TranslationConfigBase(BaseModel):
    """翻译配置基础Schema"""
    name: str = Field(..., max_length=100)
    provider: str = Field(..., description="'baidu', 'deeplx', 'ai'")
    credentials: Dict[str, Any]

    @validator('provider')
    def validate_provider(cls, v):
        allowed_providers = ['baidu', 'deeplx', 'ai']
        if v not in allowed_providers:
            raise ValueError(f'翻译服务商必须是以下之一: {", ".join(allowed_providers)}')
        return v

class TranslationConfigCreate(TranslationConfigBase):
    """创建翻译配置Schema"""

    @validator('credentials')
    def validate_credentials(cls, v, values):
        provider = values.get('provider')
        if not provider:
            # provider 验证失败时，跳过此验证
            return v

        if provider in ['baidu']:
            if not v.get('appId') or not v.get('secretKey'):
                raise ValueError("百度翻译需要 'appId' 和 'secretKey'")
        
        elif provider == 'deeplx':
            if not v.get('url'):
                raise ValueError("DeeplX翻译需要 'url'")
        
        elif provider == 'ai':
            if not v.get('url') or not v.get('key') or not v.get('model'):
                raise ValueError("AI翻译需要 'url', 'key' 和 'model'")

        return v

class TranslationConfigUpdate(BaseModel):
    """更新翻译配置Schema"""
    name: Optional[str] = Field(None, max_length=100)
    provider: Optional[str] = None
    credentials: Optional[Dict[str, Any]] = None

    @validator('provider')
    def validate_provider(cls, v):
        if v is not None:
            allowed_providers = ['baidu', 'deeplx', 'ai']
            if v not in allowed_providers:
                raise ValueError(f'翻译服务商必须是以下之一: {", ".join(allowed_providers)}')
        return v

class TranslationConfigResponse(TranslationConfigBase):
    """翻译配置响应Schema"""
    id: int
    user_id: int
    is_shared: bool
    
    class Config:
        from_attributes = True